//
//  Route.swift
//  Bee
//
//  Created by zhujinhui on 15/12/29.
//  Copyright © 2015年 kyson. All rights reserved.
//

import UIKit

private let sharedInstance = Route()

class Route: NSObject {
    
    var pageInfos:NSArray?

    override init() {
        let manifestPath = NSBundle.mainBundle().pathForResource("AppManifest", ofType: "plist")
        if(nil == manifestPath){
            let exception = NSException(name:"nil exception", reason:"AppManifest not found", userInfo:["key":"value"])
            exception.raise()
        }else{
            print("AppManifest Create Success")
        }
        
        self.pageInfos = NSArray(contentsOfFile: manifestPath!)
    }
    
    class var shareRoute : Route {
        return sharedInstance
    }
    
    func startViewControllerWithViewModel(fromViewController: KSViewController,toViewModel: BaseViewModel){
        if((fromViewController.navigationController) != nil){
            let toViewControllerName = self.findViewControllerInfoByViewModel(toViewModel)
            //获取命名空间
            let namespace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
            let clsName = namespace + "." + toViewControllerName

            let viewControllerClass: AnyObject.Type = NSClassFromString(clsName)!
            let instanceType = viewControllerClass as! KSViewController.Type
            let instance: KSViewController = instanceType.init(nibName: toViewControllerName, bundle: nil)
            instance.viewModel = toViewModel
            instance.viewModelDidBinded()
            fromViewController.navigationController!.pushViewController(instance, animated: true)
        }
        
    }
    
    private func findViewControllerInfoByViewModel(viewModelName: BaseViewModel)->String{
        let distinceViewModelClassName = NSStringFromClass(viewModelName.dynamicType).componentsSeparatedByString(".").last;
        
        for page in pageInfos!{
            let viewModelName = page["viewModel"] as! String
            if(distinceViewModelClassName == viewModelName){
                let controllerName = page["viewController"] as! String

                return controllerName
            }
        }
        return "";

    }
    
}
